package com.testing;

import com.testing.sqlUtil.MysqlUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

/**
 * @Classname ${NAME}
 * @Description 类型说明
 * @Date 2021/1/8 16:53
 * @Created by 勾勾
 */
@WebServlet(name = "GetUserInfo")
public class GetUserInfo extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/plain;charset=utf-8");
        response.setCharacterEncoding("UTF-8");

        HttpSession session = request.getSession();
        String sessionId = session.getId();


        //服务器随着请求的建立，创建一个session:  request.getSession()
        //login中记录了键值对的形式的信息 键"loginName",值"user"， session.setAttribute("loginName", user);
        //下面判断session中是否已经记录了登录用户的信息
        if (request.getSession().getAttribute("loginName")!=null){
            //已经登录
            //从session中获取记录的用户名，用于完成用户信息的查询
            MysqlUtils GG=new MysqlUtils();
            GG.createConnector();
            //调用getUserInfo()方法 获取到{nickname=roy, id=52, describe=哈哈, pwd=123456, username=roy}
            Map<String, String> userInfoMap = GG.getUserInfo(request.getSession().getAttribute("loginName").toString());
            String jsonResult="{";
            //遍历map所有的键
            for (String key : userInfoMap.keySet()) {
                //密码和用户名不返回
                if(!key.equals("pwd")&&!key.equals("username")){
                    jsonResult+="\""+key+"\":\""+userInfoMap.get(key)+"\",";
                }
            }
            jsonResult+="}";
            jsonResult=jsonResult.replaceAll(",}","}");
            response.getWriter().append(jsonResult);
 //           jsonResult=jsonResult.replaceAll("}","\"\\\"\"+sessionId+\"\\\"\"+\"\\\"=\\\"\"+sessionId+\"}\"");





        }
        else{
            //没有登录
            response.getWriter().append("{\"status\":-1,\"msg\":\"" + "您还没没有登录，不能查询用户信息" + "\"}");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().append("{\"status\":-1,\"msg\":\"" + "不支持使用get方法进行用户信息查询" + "\"}");
    }
}

